#!/usr/bin/env python3
"""
演示版向量库操作系统启动脚本
完全独立运行，不依赖外部数据库和Milvus
"""
import os
import sys
import logging
from pathlib import Path
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
import uvicorn
import json
import uuid
from datetime import datetime

# 添加项目路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

# 内存存储
demo_files = []
demo_vectors = []

# 创建FastAPI应用
app = FastAPI(
    title="向量库操作系统 - 演示版",
    description="文件管理、向量库和检索系统（演示模式）",
    version="1.0.0-demo"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/", response_class=HTMLResponse)
async def root():
    """根路径 - 返回Web界面"""
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>向量库操作系统 - 演示版</title>
        <meta charset="utf-8">
        <style>
            body { font-family: Arial, sans-serif; margin: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
            .container { max-width: 800px; margin: 0 auto; }
            .header { text-align: center; margin-bottom: 40px; }
            .card { background: white; color: #333; padding: 30px; border-radius: 15px; margin: 20px 0; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }
            .upload-area { border: 2px dashed #ddd; border-radius: 10px; padding: 40px; text-align: center; margin: 20px 0; }
            .search-box { display: flex; gap: 10px; margin: 20px 0; }
            .search-input { flex: 1; padding: 12px; border: 2px solid #ddd; border-radius: 25px; font-size: 16px; }
            .search-btn { background: #667eea; color: white; border: none; padding: 12px 24px; border-radius: 25px; cursor: pointer; }
            .result-item { background: #f8f9fa; border-radius: 8px; padding: 15px; margin: 10px 0; border-left: 4px solid #667eea; }
            .demo-notice { background: #fff3cd; color: #856404; padding: 15px; border-radius: 8px; margin: 20px 0; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>🚀 向量库操作系统 - 演示版</h1>
                <p>文件管理、向量库和检索系统</p>
            </div>
            
            <div class="demo-notice">
                <strong>演示模式说明：</strong><br>
                • 此版本为演示模式，数据存储在内存中<br>
                • 支持文件上传和基础文本处理<br>
                • 向量检索功能模拟运行<br>
                • 重启后数据会丢失
            </div>
            
            <div class="card">
                <h2>📁 文件上传</h2>
                <div class="upload-area" id="upload-area">
                    <p>拖拽文件到此处或点击选择文件</p>
                    <p style="font-size: 12px; color: #999;">支持文本文件 (.txt)</p>
                    <input type="file" id="file-input" style="display: none;" accept=".txt">
                    <button onclick="document.getElementById('file-input').click()" class="search-btn">选择文件</button>
                </div>
                <div id="upload-status"></div>
            </div>
            
            <div class="card">
                <h2>🔍 文档检索</h2>
                <div class="search-box">
                    <input type="text" id="search-input" class="search-input" placeholder="输入搜索关键词...">
                    <button class="search-btn" onclick="performSearch()">搜索</button>
                </div>
                <div id="search-results">
                    <p style="text-align: center; color: #999;">输入关键词开始搜索</p>
                </div>
            </div>
            
            <div class="card">
                <h2>📊 系统状态</h2>
                <p>已上传文件: <span id="file-count">0</span> 个</p>
                <p>向量总数: <span id="vector-count">0</span> 个</p>
                <p>运行模式: 演示模式</p>
            </div>
        </div>
        
        <script>
            // 文件上传
            document.getElementById('file-input').addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    uploadFile(file);
                }
            });
            
            async function uploadFile(file) {
                const formData = new FormData();
                formData.append('file', file);
                
                document.getElementById('upload-status').innerHTML = '<p style="color: #667eea;">正在上传...</p>';
                
                try {
                    const response = await fetch('/api/v1/files/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        document.getElementById('upload-status').innerHTML = '<p style="color: green;">✅ 上传成功</p>';
                        updateStats();
                    } else {
                        document.getElementById('upload-status').innerHTML = '<p style="color: red;">❌ 上传失败: ' + result.error + '</p>';
                    }
                } catch (error) {
                    document.getElementById('upload-status').innerHTML = '<p style="color: red;">❌ 上传失败: ' + error.message + '</p>';
                }
            }
            
            // 搜索功能
            async function performSearch() {
                const query = document.getElementById('search-input').value.trim();
                const resultsDiv = document.getElementById('search-results');
                
                if (!query) {
                    resultsDiv.innerHTML = '<p style="text-align: center; color: #999;">请输入搜索关键词</p>';
                    return;
                }
                
                resultsDiv.innerHTML = '<p style="text-align: center; color: #667eea;">正在搜索...</p>';
                
                try {
                    const response = await fetch('/api/v1/search', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            query: query,
                            top_k: 10
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        displaySearchResults(result.results);
                    } else {
                        resultsDiv.innerHTML = '<p style="color: red;">❌ 搜索失败: ' + result.error + '</p>';
                    }
                } catch (error) {
                    resultsDiv.innerHTML = '<p style="color: red;">❌ 搜索失败: ' + error.message + '</p>';
                }
            }
            
            function displaySearchResults(results) {
                const resultsDiv = document.getElementById('search-results');
                
                if (results.length === 0) {
                    resultsDiv.innerHTML = '<p style="text-align: center; color: #999;">未找到相关结果</p>';
                    return;
                }
                
                let html = '<div style="margin-bottom: 10px; color: #666;">找到 ' + results.length + ' 个结果</div>';
                
                results.forEach((result, index) => {
                    html += `
                        <div class="result-item">
                            <div style="font-weight: bold; color: #667eea;">${result.filename} (第${index + 1}名)</div>
                            <div style="color: #666; margin: 10px 0;">${result.content.substring(0, 200)}...</div>
                            <div style="color: #999; font-size: 12px;">相似度: ${(result.score * 100).toFixed(1)}%</div>
                        </div>
                    `;
                });
                
                resultsDiv.innerHTML = html;
            }
            
            // 更新统计信息
            async function updateStats() {
                try {
                    const response = await fetch('/api/v1/system/stats');
                    const data = await response.json();
                    
                    document.getElementById('file-count').textContent = data.files?.total || 0;
                    document.getElementById('vector-count').textContent = data.vectors?.total_chunks || 0;
                } catch (error) {
                    console.error('获取统计信息失败:', error);
                }
            }
            
            // 页面加载时更新统计
            updateStats();
        </script>
    </body>
    </html>
    """

@app.post("/api/v1/files/upload")
async def upload_file(file: UploadFile = File(...)):
    """上传文件"""
    try:
        # 读取文件内容
        content = await file.read()
        text_content = content.decode('utf-8', errors='ignore')

        # 创建文件记录
        file_record = {
            "file_id": str(uuid.uuid4()),
            "filename": file.filename,
            "content": text_content,
            "file_size": len(content),
            "upload_time": datetime.now().isoformat(),
            "chunks": [{"content": text_content, "chunk_id": "demo_chunk_1"}]
        }

        demo_files.append(file_record)

        return {
            "success": True,
            "file_id": file_record["file_id"],
            "filename": file.filename,
            "message": "文件上传成功（演示模式）"
        }

    except Exception as e:
        logger.error(f"文件上传失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/v1/search")
async def search(request: dict):
    """搜索"""
    try:
        query = request.get("query", "")
        top_k = request.get("top_k", 10)

        if not query:
            return {
                "success": False,
                "error": "查询文本不能为空"
            }

        # 模拟搜索结果
        results = []
        for file_record in demo_files:
            # 简单的关键词匹配
            if query.lower() in file_record["content"].lower():
                results.append({
                    "id": len(results) + 1,
                    "score": 0.8 + (len(results) * 0.1),  # 模拟相似度分数
                    "content": file_record["content"][:200] + "...",
                    "file_id": file_record["file_id"],
                    "chunk_id": "demo_chunk_1",
                    "chunk_index": 0,
                    "file_type": "txt",
                    "filename": file_record["filename"],
                    "metadata": {},
                    "created_time": int(datetime.now().timestamp())
                })

                if len(results) >= top_k:
                    break

        return {
            "success": True,
            "query": query,
            "results": results,
            "total_found": len(results),
            "total_returned": len(results),
            "search_time": 0.1,
            "similarity_threshold": 0.05
        }

    except Exception as e:
        logger.error(f"搜索失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/v1/system/stats")
async def get_system_stats():
    """获取系统统计信息"""
    return {
        "files": {
            "total": len(demo_files),
            "processed": len(demo_files),
            "failed": 0
        },
        "vectors": {
            "total_chunks": len(demo_files),
            "milvus_entities": 0
        },
        "file_types": [
            {"type": "txt", "count": len(demo_files)}
        ],
        "milvus": {
            "status": "演示模式"
        },
        "cache": {
            "enabled": False,
            "status": "演示模式"
        }
    }

@app.get("/health")
async def health():
    """健康检查"""
    return {
        "status": "healthy",
        "version": "1.0.0-demo",
        "mode": "演示模式"
    }

def main():
    """主函数"""
    print("=" * 60)
    print("🚀 向量库操作系统 - 演示版")
    print("=" * 60)
    print("📁 文件管理、文本处理和基础检索系统")
    print("⚠️  演示模式：数据存储在内存中")
    print("=" * 60)

    print("✅ 系统初始化完成")
    print("🚀 启动Web服务...")
    print("📱 访问地址: http://localhost:8000")
    print("📚 API文档: http://localhost:8000/docs")

    # 启动服务
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        reload=False
    )

if __name__ == "__main__":
    main()
